package com.demo.springboot.job;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.demo.springboot.entity.UserEntity;
import com.demo.springboot.listener.MyNormalListener;
import com.demo.springboot.service.UserService;
import com.demo.springboot.sharding.MyShardingStrategy;
import com.elasticjob.annotation.ElasticSimpleJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalTime;
import java.util.Date;

/**
 * @author wangfengchen
 * 简单任务，实现SimpleJob接口，实现execute方法，里面是具体任务逻辑
 */
@Slf4j
@ElasticSimpleJob(
    jobName = "mySimpleJob",
    cron = "0/5 * * * * ?",
    shardingTotalCount = 2,
    overwrite = true,
    jobStrategy = MyShardingStrategy.class,
    jobEvent = false,
    jobListener = {MyNormalListener.class}
)
public class MySimpleJob implements SimpleJob {

  @Autowired
  private UserService userService;


  @Override
  public void execute(ShardingContext shardingContext) {
    LocalTime time = LocalTime.now();
    System.out.println(time + "，我是分片项：" + shardingContext.getShardingItem() +
        "，总分片项：" + shardingContext.getShardingTotalCount() + "，taskId" +
        shardingContext.getTaskId());

    UserEntity userEntity = new UserEntity().setId(IdUtil.getSnowflakeNextId())
        .setUsername("test")
        .setPhone("1")
        .setAge(RandomUtil.randomInt(100))
        .setCreateTime(new Date());
    userService.save(userEntity);
  }

}
